package com.financial.business.integral.service.yd.impl;

import com.financial.business.integral.config.UrlConfig;
import com.financial.business.integral.config.YDAccessTokenConfig;
import com.financial.business.integral.connector.SysconfigFeign;
import com.financial.business.integral.constants.FinancialRefundIntegralEnumConstants;
import com.financial.business.integral.dao.FinancialYDRefundIntegralDao;
import com.financial.business.integral.domain.FinancialYDRefundIntegralDO;
import com.financial.business.integral.dto.FinancialYDIntegralRefundDTO;
import com.financial.business.integral.service.impl.FinancialIntegralRefundServiceImpl;
import com.financial.business.integral.service.yd.FinancialYDIntergralRefundService;
import com.financial.business.integral.utils.*;
import com.financial.business.integral.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Davidbieber
 * @description 金融中心积分退款业务接口实现类
 * @email davidbieber@163.com
 * @date 2019/12/12 8:55 AM
 */
@Service
public class FinancialYDIntegralRefundServiceImpl implements FinancialYDIntergralRefundService {
    protected static final Logger logger = LoggerFactory.getLogger(FinancialIntegralRefundServiceImpl.class);

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private YDAccessTokenConfig ydAccessTokenConfig;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FinancialYDRefundIntegralDao financialYDRefundIntegralDao;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Override
    public ApiResult refund(String requestParam) {
        logger.info("FinancialIntegralRefundServiceImpl.refund()-----获取积分支付退款类型为：" + requestParam);
        FinancialYDIntegralRefundDTO financialIntegralRefundDTO = JsonUtils.convertBean(requestParam, FinancialYDIntegralRefundDTO.class);
        Map<String, Object> params = JsonUtils.jsonToMap(requestParam);
        /*用户ID*/
        Object tempParam = params.get("customer_id");
        String customerId = tempParam == null ? null : tempParam.toString();
        /*支付id*/
        tempParam = params.get("pay_id");
        String payId = tempParam == null ? null : tempParam.toString();
        /*退款金额*/
        tempParam = params.get("total_amount");
        String totalAmountStr = tempParam == null ? null : tempParam.toString();
        /*退款原因*/
        tempParam = params.get("refund_reason");
        String refundReason = tempParam == null ? null : tempParam.toString();
        /*获取token*/
        tempParam = params.get("authorization");
        String authorization = tempParam == null ? null : tempParam.toString();
        /*现在支付渠道类型编码*/
        tempParam = params.get("pay_channel_no");
        String payChannelNo = tempParam == null ? null : tempParam.toString();
        /*退款交易单号*/
        tempParam = params.get("out_trade_no");
        String outTradeNo = tempParam == null ? null : tempParam.toString();
        /*退款单号*/
        tempParam = params.get("refund_no");
        String refundNo = tempParam == null ? null : tempParam.toString();
        /*对接平台商户号*/
        tempParam = params.get("store_no");
        String storeNo = tempParam == null ? null : tempParam.toString();
        /*退款类型*/
        tempParam = params.get("refund_type");
        String refundType = tempParam == null ? null : tempParam.toString();
        /*异步回调地址*/
        tempParam = params.get("notify_url");
        String notifyUrl = tempParam == null ? null : tempParam.toString();

        if (org.apache.commons.lang3.StringUtils.isBlank(customerId) || org.apache.commons.lang3.StringUtils.isBlank(payId)
                || org.apache.commons.lang3.StringUtils.isBlank(totalAmountStr) || org.apache.commons.lang3.StringUtils.isBlank(notifyUrl)
                || org.apache.commons.lang3.StringUtils.isBlank(refundReason) || org.apache.commons.lang3.StringUtils.isBlank(payChannelNo)
                || org.apache.commons.lang3.StringUtils.isBlank(authorization) || org.apache.commons.lang3.StringUtils.isBlank(outTradeNo)
                || org.apache.commons.lang3.StringUtils.isBlank(refundNo) || org.apache.commons.lang3.StringUtils.isBlank(storeNo)
                || org.apache.commons.lang3.StringUtils.isBlank(refundType)) {
            /*对所传字段进行非空校验判断*/
            return ApiResult.failure(ValidateUtils.validateProperty(financialIntegralRefundDTO));
        }
        try {
            /*获取够样支付平台信息*/
            ApiResult apiResult = sysconfigFeign.platfromInfo(payChannelNo);
            String apiResultMsg = (String) apiResult.getResult();
            if (apiResult.getCode() == FinancialRefundIntegralEnumConstants.ENUM_CODE_SUC || (apiResultMsg != null && apiResultMsg != "")) {
                /*获取每个参数信息*/
                Map<String, Object> map = JsonUtils.jsonToMap(apiResultMsg);
                String platfromNo = (String) map.get("platfrom_no");
                String platformName = (String) map.get("platform_name");
                String passWord = (String) map.get("pass_word");
                String secret = (String) map.get("secret");
                String salt = (String) map.get("salt");
                /*缓存中获取token*/
                String resultAccessToken;
                Object object = redisUtils.getValue("financialYDRefundAccessToken");
                if (null == object) {
                    /*对参数进行验签加密*/
                    resultAccessToken = ydAccessTokenConfig.getYDRefundAccessToken(platformName,passWord,secret,platfromNo);
                } else {
                    resultAccessToken = (String) object;
                }
                /*对分账所有的金额进行精确度设置，保留两位小数*/
                /*支付总金额*/
                BigDecimal totalAmount = new BigDecimal(totalAmountStr).setScale(2, RoundingMode.HALF_UP);
                FinancialYDRefundIntegralDO financialYDRefundIntegralDO = new FinancialYDRefundIntegralDO();
                financialYDRefundIntegralDO.setCustomerId(customerId);
                financialYDRefundIntegralDO.setGmtCreate(new Date());
                financialYDRefundIntegralDO.setGmtModified(new Date());
                financialYDRefundIntegralDO.setIsDelete(FinancialRefundIntegralEnumConstants.ENUM_ISDELETE_UNDEL);
                financialYDRefundIntegralDO.setOutTradeNo(outTradeNo);
                financialYDRefundIntegralDO.setPlatformNo(platfromNo);
                financialYDRefundIntegralDO.setRefundNo(refundNo);
                financialYDRefundIntegralDO.setResqContent(requestParam);
                financialYDRefundIntegralDO.setReturnMessage(FinancialRefundIntegralEnumConstants.ENUM_STATE_FAIL);
                financialYDRefundIntegralDO.setState(FinancialRefundIntegralEnumConstants.ENUM_STATE_WAIT);
                financialYDRefundIntegralDO.setStoreNo(storeNo);
                financialYDRefundIntegralDO.setTotalAmount(totalAmount);
                financialYDRefundIntegralDO.setNotify_url(notifyUrl);
                int res = financialYDRefundIntegralDao.save(financialYDRefundIntegralDO);
                if (res > 0) {
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----保存金融中心数据信息成功！");
                    /*拼接请求参数对接优店平台*/
                    Map<String, Object> requestMap = new HashMap<>();
                    /*prePayNo,customerId,payId,backCurrency*/
                    /*customerId、backCurrency、prePayNo、Authorization、platfromMarking、payId*/
                    requestMap.put("customerId", customerId);
                    requestMap.put("backCurrency", totalAmount);
                    requestMap.put("prePayNo", outTradeNo);
                    requestMap.put("platfromMarking", platfromNo);
                    requestMap.put("payId", payId);
                    requestMap.put("tgAccessToken",resultAccessToken);
                    requestMap.put("refundReason",refundReason);
                    //余额平台回调地址
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----拼接积分退款请求参数对接够样平台:" + JsonUtils.objectToJson(requestMap));
                    Map<String, String> omap = new HashMap<>();
                    omap.put("Authorization",authorization);
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----拼接请求参数对接够样积分平台请求地址:{},对接参数:{},携带token:{}", UrlConfig.INTEGRAL_YD_REFUND_URL, JsonUtils.objectToJson(requestMap),omap);
                    String result = httpClientUtils.doPostToJson(UrlConfig.INTEGRAL_YD_REFUND_URL, requestMap,omap);
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----customerUuid:{},积分退款信息结果:{}",customerId,result);
                    Map<String, Object> resultMap = JsonUtils.jsonToMap(result);
                    if (!FinancialRefundIntegralEnumConstants.ENUM_YDRETURNCODE_SUC.equals(resultMap.get("return_code"))) {
                        ApiResult.failure("请求金融中心余额退款接口失败");
                    }
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----请求金融中心积分退款接口结果为:" + JsonUtils.jsonToMap(result));
                    String prePayInfoMsg = resultMap.get("prePayInfoDO").toString();
                    /*更改数据库状态*/
                    Map<String, Object> updateMap = new HashMap();
                    updateMap.put("outTradeNo", outTradeNo);
                    updateMap.put("state", FinancialRefundIntegralEnumConstants.ENUM_STATE_SUC);
                    updateMap.put("gmtModified", new Date());
                    updateMap.put("returnMessage", result);
                    financialYDRefundIntegralDao.updateInfo(updateMap);
                    /*返回信息给调用端*/
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----返回信息给调用端:" + prePayInfoMsg);
                    return ApiResult.success(prePayInfoMsg);
                } else {
                    logger.info("FinancialYDIntegralRefundServiceImpl.refund()-----保存金融中心数据信息失败！");
                    return ApiResult.failure(requestParam);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialYDIntegralRefundServiceImpl.refund()-----金融中心数据信息失败:" + e.getMessage());
        }
        return ApiResult.failure(requestParam);
    }
}
